package com.lap.framework.junit.application.builder;

import com.lap.framework.junit.configure.EnvConfigure;
import com.lap.framework.junit.domain.ClassInfo;
import com.lap.framework.junit.shared.tool.ProjectUtil;
import java.io.File;
import java.util.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DefaultBuilder extends ClassBuilder {

  private final List<ClassInfo> classInfoList = new ArrayList<>();
  private final JavaFileScanner fileScanner;
  private final ClassParser classParser;

  public DefaultBuilder() {
    this(new JavaFileScanner(), new ClassParser());
  }

  // 可以用于依赖注入的构造函数
  public DefaultBuilder(JavaFileScanner fileScanner, ClassParser classParser) {
    this.fileScanner = fileScanner;
    this.classParser = classParser;
  }

  @Override
  public void builder(EnvConfigure configure) {
    configure
        .getBasePackages()
        .forEach(
            basePackage -> {
              File parentPath = new File(ProjectUtil.getJavaPath(basePackage));
              if (parentPath.exists() && parentPath.isDirectory()) {
                fileScanner
                    .scanJavaFiles(configure, parentPath)
                    .forEach(file -> parseFile(configure, basePackage, file));
              } else {
                log.warn("Directory does not exist: {}", parentPath.getAbsolutePath());
              }
            });
  }

  private void parseFile(EnvConfigure env, String basePackage, File file) {
    classParser.parseClass(env, basePackage, file).ifPresent(classInfoList::add);
  }

  @Override
  public List<ClassInfo> getClasses() {
    return Collections.unmodifiableList(classInfoList);
  }
}
